<template>
  <div>
    <!-- 面包屑导航栏 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/">用户管理</a></el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <el-row :gutter="20">
        <!-- 搜索区域 -->
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDlalogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表 -->
      <el-table :data="userlist" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="邮箱" prop="email"></el-table-column>
        <el-table-column label="电话" prop="mobile"></el-table-column>
        <el-table-column label="角色" prop="role_name"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.mg_state" @change="userStatuChange(scope.row)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180px">
          <template slot-scope="scope">
            <!-- 编辑 -->
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="showEditDialog(scope.row.id)"
            ></el-button>
            <!-- 删除 -->
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="removeUserByid(scope.row.id)"
            ></el-button>
         <!-- 分配 -->
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top-start"
              :enterable= "false"
            
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                  @click="setRole(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- //分页功能 -->
       <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[2, 3, 5, 10]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total">
    </el-pagination>
    </el-card>
    
    <!-- 添加用户对话框 -->
    <el-dialog
  title="添加用户"
  :visible.sync="addDlalogVisible"
  width="50%"  @close="addDlalogClose">
  <!-- 主体区域 -->
 <el-form :model="addForm" :rules="addFormRules" ref="addFormRef"
   label-width="70px" >
  <el-form-item label="用户名" prop="username">
    <el-input v-model="addForm.username"></el-input>
  </el-form-item>
  <el-form-item label="密码" prop="password" >
    <el-input v-model="addForm.password" type="password"></el-input>
  </el-form-item>
  <el-form-item label="邮箱" prop="email">
    <el-input v-model="addForm.email"></el-input>
  </el-form-item>
  <el-form-item label="手机" prop="mobile">
    <el-input v-model.trim="addForm.mobile"></el-input>
  </el-form-item>
 </el-form>

  <span slot="footer" class="dialog-footer">
    <el-button @click="addDlalogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUsers">确 定</el-button>
  </span>
</el-dialog>

   <!-- 修改用户对话框 -->
   <el-dialog
  title="修改用户"
  :visible.sync="editDialogVisible"
  width="50%" @close="editDialogClosed">
  <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
  <el-form-item label="用户名" >
    <el-input v-model="editForm.username" disabled></el-input>
  </el-form-item>
  <el-form-item label="邮箱" prop="email" >
    <el-input v-model="editForm.email" ></el-input>
  </el-form-item>
  <el-form-item label="手机号" prop="mobile">
    <el-input v-model="editForm.mobile" ></el-input>
  </el-form-item>
  </el-form>

  <span slot="footer" class="dialog-footer">
    <el-button @click="editDialogVisible  = false">取 消</el-button>
    <el-button type="primary" @click="editUserInfo">确 定</el-button>
  </span>
</el-dialog>

<!-- 分配角色对话框 -->
<el-dialog
  title="分配角色"
  :visible.sync="setRoleDialogVisible"
  width="50%" @close="setRoleDialogClosed">
   <div>
     <p>当前用户:{{userinfo.username}}</p>
     <p>当前的角色:{{userinfo.role_name}}</p>
     <p>分配新角色 
        <el-select v-model="selectedRoleId" placeholder="请选择">
    <el-option
      v-for="item in roleList"
      :key="item.id"
      :label="item.roleName"
      :value="item.id">
    </el-option>
  </el-select>
     </p>
   </div>
  <span slot="footer" class="dialog-footer">
    <el-button @click="setRoleDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    //校验邮箱规则
    var checkEmil = (rule,value,cb) =>{
      const regEmai = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if(regEmai.test(value)) {
        // 正确的邮箱
        return cb()
      }
      cb(new Error('请输入正确的邮箱格式'))
    }
    //校验手机号码
    var checkMobile = (rule,value,cb) => {
      const regMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
       if(regMobile.test(value))  return cb()
       cb(new Error('请输入正确的手机号码'))
    }
    return {
      //用户列表参数
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      //用户数据
      userlist: [],
      //总条数
      total: 0,
      //控制添加对话框的开关
      addDlalogVisible : false,
      //添加用户的表单数据
       addForm : {
        username : '',
        password : '',
        email : '',
        mobile : ''
      },
      //校验表单数据
      addFormRules : {
        username : [
            { required: true, message: '请输入用户名', trigger: 'blur' },
            { min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ],
        password :[
           { required: true, message: '请输入密码', trigger: 'blur' },
            { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email : [
           { required: true, message: '请输入邮箱', trigger: 'blur' },
           { validator:checkEmil,trigger:'blur'}
        ],
        mobile : [
           { required: true, message: '请输入手机号码', trigger: 'blur' },
              { validator:checkMobile,trigger:'blur'}
        ]
      },
      //控制修改用户对话框的开关
      editDialogVisible   : false,
      //根据id获取到的用户数据
      editForm: {},
      //修改用户的校验
      editFormRules :{
          email : [
           { required: true, message: '请输入邮箱', trigger: 'blur' },
           { validator:checkEmil,trigger:'blur'}
        ],
        mobile : [
           { required: true, message: '请输入手机号码', trigger: 'blur' },
              { validator:checkMobile,trigger:'blur'}
        ]
      },
      //分配角色对话框
      setRoleDialogVisible : false,
      //需要被分配的角色
      userinfo : {},
      //角色列表数据
       roleList : [],
       //选中的角色数据
      selectedRoleId :''
    };
  },
  created() {
    this.getUserList();
  },
  methods: {
    //请求用户列表数据
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo,
      });
      // console.log(res);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.userlist = res.data.users;
      this.total = res.data.total;
    },
    // pagination 变化
    handleSizeChange(nweSize) {
    //  console.log(nweSize);
     this.queryInfo.pagesize = nweSize
     
     this.getUserList() 
    },
    // 页面值变化
    handleCurrentChange(newPage) {
      // console.log(newPage);
     this.queryInfo.pagenum = newPage
    this.getUserList() 
    },
    //修改角色状态
  async userStatuChange(userinfo) {
      //  console.log(userinfo);
     const {data:res} = await   this.$http.put(`users/${userinfo.id}/state/${userinfo.mg_state}`)
      if(res.meta.status !==200) {
        userinfo.mg_state =  ! userinfo.mg_state
         return this.$message.error('更新状态失败')
      }
     
    },
    //监听添加用户对话框的事件
    addDlalogClose() {
      this.$refs.addFormRef.resetFields()
    },
    //添加用用户 确认按钮
  addUsers() {
      //校验表单数据
          this.$refs.addFormRef.validate(async  valid => {
            if(!valid) return
            //验证成功请求数据
          const {data:res} = await this.$http.post('users' , this.addForm )
          // console.log(res);
          if(res.meta.status !== 201) return this.$message.error(res.meta.msg)
          this.$message.success('添加成功')
          //隐藏对话框
          this.addDlalogVisible = false
          //重新渲染页面
          this.getUserList()
          })
    },
    //修改用户 数据信息
  async  showEditDialog(id) {
     //调用接口 获取用户信息
    const {data:res} = await this.$http.get('users/' + id)
    if(res.meta.status !==200) return this.$message.error(res.meta.msg)
    this.editForm = res.data
    // console.log(res);
     this.editDialogVisible  = true
    },
    //监听修改用户关闭的 事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    //修改用户信息的提交按钮
    editUserInfo() {
      this.$refs.editFormRef.validate(async valid => {
      const {data:res} = await  this.$http.put('users/' +this.editForm.id ,this.editForm)
       console.log(res);
       if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
       this.$message.success(res.meta.msg)
       //重新渲染数据
       this.getUserList()
       //关闭对话框
       this.editDialogVisible = false
       })
    },
    //删除用户
  async  removeUserByid(id) {
      //询问用户是否删除
     const confirmResult =await this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'}).catch(err => err)
          //判断用户是否点击确定或取消
          if(confirmResult !== 'confirm') return this.$message.info('已取消删除')
          //调用接口删除数据
        const {data:res} = await  this.$http.delete('users/' + id)
        if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        //重新渲染数据
         this.getUserList()
      
         
    },
    //分配角色
  async  setRole(userinfo) {
      this.userinfo = userinfo
      //调用接口获取到 角色列表
   const {data:res} = await   this.$http.get('roles')
   if(res.meta.status!==200) return this.$message.error(res.meta.msg)
   this.roleList = res.data
      this.setRoleDialogVisible = true
    },
    //分配角色提交按钮
  async saveRoleInfo() {
     if(!this.selectedRoleId) return this.$message.error('请选择要分配的角色')
 const {data:res} = await this.$http.put(`users/${this.userinfo.id}/role`,{rid : this.selectedRoleId})
  if(res.meta.status!==200) return this.$message.error(res.meta.msg)
  this.$message.success(res.meta.msg)
 this.getUserList();
  this.setRoleDialogVisible = false
    },
    //分配角色对话框关闭事件
    setRoleDialogClosed() {
      this.selectedRoleId = ''
      this.userinfo = {}
    }
  },
};
</script>

<style lang="less" scoped></style>
>
